package com.xiebishe.mylibrary.net.okhttp;

import com.xiebishe.mylibrary.base.MyApplication;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpClientManager {

    private OkHttpClient mOkHttpClient;

    private OkHttpClient mUploadOkHttpClient;

    private static List<Interceptor> mUserInterceptors=new ArrayList<>();

    private OkHttpClientManager() {
        List<Interceptor> interceptors=new ArrayList<>();
        interceptors.add(new CommonInterceptor());
        interceptors.addAll(mUserInterceptors);
        if(MyApplication.getInstance().isDebug()){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
            interceptors.add(loggingInterceptor);
        }
        mOkHttpClient = OkHttpHelper
                .createOkHttpClient(5, 20, 0, interceptors);
        mUploadOkHttpClient = OkHttpHelper.createOkHttpClient(5, 20, 60, interceptors);
    }

    public static OkHttpClientManager getInstance() {
        return getInstance(false, null);
    }

    private static class INSTANCE_HOLDER{
        private static final OkHttpClientManager INSTANCE=new OkHttpClientManager();
    }

    public static OkHttpClientManager getInstance(boolean debug, List<Interceptor> interceptors) {
        if(interceptors!=null){
            mUserInterceptors.clear();
            mUserInterceptors.addAll(interceptors);
        }
        return INSTANCE_HOLDER.INSTANCE;
    }

    public static synchronized void setUserInterceptors(Interceptor...interceptors) {
        mUserInterceptors.clear();
        mUserInterceptors.addAll(Arrays.asList(interceptors));
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    /**
     * 获取上次okhttp管理器
     *
     * @return
     */
    public OkHttpClient getUploadOkHttpClient() {
        return mUploadOkHttpClient;
    }
}
